# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd
import string

# 二维数据:pandas.DataFrame,行:index,列:columns
rows = 5  # 行
cols = 6  # 列
df = pd.DataFrame(data=np.arange(0, rows * cols, 1).reshape(rows, cols),
                  index=list(string.ascii_lowercase[:rows]),
                  columns=list(string.ascii_uppercase[:cols]))
# print('df:----------\n', df, sep='')
shape = df.shape  # 形状:(rows, cols)->tuple
index = df.index  # 索引
columns = df.columns  # 列名


def df_slice():
    # 取行:[start:stop:step]->DataFrame
    # df1 = df[0]  # 报错:KeyError
    # df1 = df['a']  # 报错:KeyError

    df1 = df[0:1]  # 单行
    df1 = df[0:-1]  # 多行

    df1 = df[-1:]  # 最后一行
    df1 = df[::-1]  # 索引反转
    # 取奇偶行
    odd = df[0:rows:2]
    even = df[1:rows:2]

    # 取列:
    df1 = df.B  # 单列->Series
    df1 = df['B']  # 单列->Series
    df1 = df[['B']]  # 单列->DataFrame
    # df1 = df['B', 'C']  # 报错:KeyError
    df1 = df[['B', 'C']]  # 多列->DataFrame

    # 条件筛选
    # 关系运算:>, <, >=, <= , ==, !=
    df1 = df[df['A'] >= 12]
    df1 = df[[i > 12 for i in df['A']]]

    # 逻辑运算:()&(), ()|(), ~()
    # df1 = df[df['A'] >= 12 & df['A'] <= 24]  # 报错:ValueError
    # 注意逻辑运算符两边的条件使用括号()括起来
    df1 = df[(df['A'] >= 12) & (df['A'] <= 24)]

    # .isin()
    # df1 = df[df['A'].isin([12, 24])]

    df1 = df[~df['A'].isin([12, 24])]
    df1 = df[~(df['A'] == 12)]

    # .str.contains()

    print(df1.head())

    # 如果行列元素相同且类型都是整数时，df[i]结果默认取列
    data_frame = pd.DataFrame(data=np.arange(0, rows * cols, 1).reshape(rows, cols),
                              index=list(range(rows)),
                              columns=list(range(cols)))
    df1 = data_frame[0]  # 不报错，取单列->Series
    pass


def df_loc():
    """
    loc函数(locate):行名或列名
    Returns
    -------

    """
    df2 = df.loc['c']  # 单行:Series
    df2 = df.loc[['c']]  # 单行:DataFrame
    df2 = df.loc[['c', 'd']]  # 多行:DataFrame

    df2 = df.loc[:, 'C']  # 单列:Series
    df2 = df.loc[:, ['C']]  # 单列:DataFrame
    df2 = df.loc[:, ['C', 'D']]  # 多列:DataFrame

    df2 = df.loc['c', 'C']  # 元素
    df2 = df.loc['c', ['C', 'D']]  # 部分行列:Series
    df2 = df.loc[['c'], ['C', 'D']]  # 部分行列:DataFrame
    df2 = df.loc[['c', 'd'], ['C', 'D']]  # 部分行列:DataFrame

    # 条件筛选
    df2 = df.loc[df['C'] > 3]



    print(type(df2))
    print('df2:----------\n', df2, sep='')

    pass


def df_iloc():
    # iloc函数(index locate):行下标或列下标
    df3 = df.iloc[0]  # 单行:Series
    df3 = df.iloc[1:2]  # 单行:DataFrame
    df3 = df.iloc[0:10:2]  # 多行:DataFrame

    df3 = df.iloc[:, 0]  # 单列:Series
    df3 = df.iloc[:, 1:2]  # 单列:DataFrame
    df3 = df.iloc[:, 0:10:2]  # 多列:DataFrame

    df3 = df.iloc[1:2, 1:2]  # 部分行列:DataFrame
    df3 = df.iloc[1:3, 1:3]  # 部分行列:DataFrame

    print(type(df3))
    print('df3:----------\n', df3, sep='')
    pass


def df_at():
    # 元素:at函数（行是行名，列是列名）
    df4 = df.at['a', 'A']

    print(type(df4))
    print('df4:----------\n', df4, sep='')

    # iat函数（行列都要使用下标）
    df5 = df.iat[0, 0]

    print(type(df5))
    print('df5:----------\n', df5, sep='')


def rename():
    # 对行或列重命名

    # axis=0, index=

    # axis=1, columns=
    print(df.columns)
    column_dict = {'A': 'a'}
    df6 = df.rename(columns=column_dict)
    df6 = df.rename(columns=lambda x: rename_column(x))

    def rename_column(x):
        pass

    pass


def copy():
    df1 = df[df['A'].isin([0,12,24])]
    df1['A'] = df1['A'] + 1
    print(df)
    df2 = df1[df1['A'].isin([1, 25])]
    df2['A'] = df2['A'] + 1
    df3 = df2[['A', 'B']]
    df3['A'] = df3['A'] + 1

    print(df1)


if __name__ == '__main__':
    # df_slice()
    # df_loc()
    copy()

    pass
